package com.graduate.service.impl;

import com.graduate.mapper.UserMapper;
import com.graduate.mapper.UserMapperCustom;
import com.graduate.po.*;
import com.graduate.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * User
 */
@Service
public class UserServiceImpl implements UserService {

    //使用spring 自动注入
    @Autowired
    private UserMapperCustom userMapperCustom;

    @Autowired
    private UserMapper userMapper;

    public void updataById(Integer id, User user) throws Exception {
        userMapper.updateByPrimaryKey(user);
    }

    public void removeById(Integer id) throws Exception {
        userMapper.deleteByPrimaryKey(id);
    }

    public List<User> findByPaging(Integer toPageNo) throws Exception {
        PagingVO pagingVO = new PagingVO();
        pagingVO.setToPageNo(toPageNo);

        List<User> list = userMapperCustom.findByPaging(pagingVO);

        return list;
    }

    public Boolean save(User user) throws Exception {
        User currentUser = userMapper.selectByPrimaryKey(user.getUserID());
        if (currentUser == null) {
            userMapper.insert(user);
            return true;
        }

        return false;
    }

    //返回用户总数
    public int getUserCount() throws Exception {
        //自定义查询对象
        UserExample userExample = new UserExample();
        //通过criteria构造查询条件
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUseridIsNotNull();

        return (int)userMapper.countByExample(userExample);
    }

    public User findById(Integer id) throws Exception {

        User currentUser  = userMapper.selectByPrimaryKey(id);
        User userCustom = null;
        if (currentUser != null) {
            userCustom = new User();
            //类拷贝
            BeanUtils.copyProperties(currentUser, userCustom);
        }

        return userCustom;
    }

    //模糊查询
    public List<User> findByName(String name) throws Exception {

        UserExample userExample = new UserExample();
        //自定义查询条件
        UserExample.Criteria criteria = userExample.createCriteria();

        criteria.anduserNameLike("%" + name + "%");

        List<User> list = userMapper.selectByExample(userExample);

        List<User> userCustomList = null;

        if (list != null) {
            userCustomList = new ArrayList<User>();
            for (User s : list) {
                User userCustom = new User();
                //类拷贝
                BeanUtils.copyProperties(s, userCustom);

                userCustomList.add(userCustom);
            }
        }

        return userCustomList;
    }
}
